package com.example.educationblockchain.util;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import java.io.UnsupportedEncodingException;
import java.security.*;

public class ECC {

    /**
     * 生成密钥对
     *
     * @param keysize 密钥长度
     * @return
     */

    static{
        try{
            Security.addProvider(new BouncyCastleProvider());
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    static final String EC_ALGORITHM = "EC";

    static final String EC_PROVIDER = "BC";

    public static KeyPair generateECCKeyPair(int keysize) {
        try {
            // 获取指定算法的密钥对生成器

            KeyPairGenerator generator = KeyPairGenerator.getInstance(EC_ALGORITHM, EC_PROVIDER);
            // 初始化密钥对生成器（指定密钥长度, 使用默认的安全随机数源）
            generator.initialize(keysize);
            // 随机生成一对密钥（包含公钥和私钥）
            return generator.generateKeyPair();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ECC 加密
     *
     * @param publicKey 公钥
     * @param plain     原文
     * @return　密文
     */

    static final String ECIES_ALGORITHM = "ECIES";

    public static byte[] eccEncrypt(PublicKey publicKey, byte[] plain) {
        try {
            Cipher cipher = Cipher.getInstance(ECIES_ALGORITHM, EC_PROVIDER);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return cipher.doFinal(plain);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ECC 解密
     *
     * @param privateKey 　私钥
     * @param encrypted  　密文
     * @return　原文
     */
    public static byte[] eccDecrypt(PrivateKey privateKey, byte[] encrypted) {
        try {
            Cipher cipher = Cipher.getInstance(ECIES_ALGORITHM, EC_PROVIDER);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            return cipher.doFinal(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
